<?php
use Illuminate\Database\Eloquent\SoftDeletingTrait;

class Customer extends Eloquent
{
	use SoftDeletingTrait;

	public $timestamps   = true;
	protected $dates     = ['deleted_at'];
	protected $table     = 'customer';
	protected $validator = null;

	public function saveData($data)
	{
		$customer = new Customer;

		if(isset($data['id'])){
			$customer = Customer::firstOrCreate(array('id' => $data['id']));
		}
		
		$customer->name          = $data['name'];
		$customer->address       = $data['address'];
		$customer->phone         = $data['phone'];
		$customer->order         = $data['order'];
		$customer->type          = $data['type'];
		$customer->discount      = $data['discount'];
		$customer->address_print = $data['address_print'];

		$customer->save();

		return $customer;
	}

	public function getDatas($page = 0, $limit = 10)
	{
		$customers = Customer::all();

		return $customers;
	}

	public function scopeCustomers($query){
		$result = $query->whereType('customer')->orderBy('order')->get();

		return $result;
	}

	public function scopeSuppliers($query){
		$result = $query->whereType('supplier')->orderBy('order')->get();

		return $result;
	}

	public function validator($data)
	{
		$id = (isset($data['id']))? $data['id'] : "NULL";

		$rules = array(
				'name' => 
					array(
						'required', 
						'unique:customer,name,' . $id . ',id,type,' . $data['type'] . ',deleted_at,NULL',
						'alpha_num_spaces',
					),
				'address' => 
					array(
						'alpha_num_spaces',
					),
				'phone' => 
					array(
						'numeric',
					),
				'order' => 
					array(
						'required', 
						'numeric',
						'min:0',
					),
				'discount' => 
					array(
						'required', 
						'numeric',
						'min:0',
					),
				);

		$this->validator = Validator::make($data, $rules);

		return $this->validator;
	}

	public function getValidatorMessage(){
		$messages = $this->validator->messages();
		
		$result   = array();

		foreach($messages->all() as $m){
			$result[]['message'] = $m;
		}

		return $result;
	}
}